import {Toast} from "vant";
import axios, {AxiosError, AxiosInstance} from "axios";

import {localCache} from "@/utils";
import useMyModule from "@/store/myModule";
import {IResponseData, ZJRequestConfig} from "@/services/types";

class ZJRequest {
    request: AxiosInstance
    count: number
    myModule: any
    needToast: boolean // 默认不需要提示弹窗，只显示加载的弹窗

    constructor(config?: ZJRequestConfig) {
        this.count = 0
        this.needToast = false
        this.request = axios.create(config)
        // 添加请求拦截器
        this.request.interceptors.request.use(async (interceptorsConfig: ZJRequestConfig) => {
            this.count += 1
            this.myModule = useMyModule()
            /*
             this.toast = Toast.loading({
                duration: 0,
                message: '加载中...',
                forbidClick: true
            });
             */
            if (interceptorsConfig?.needToken) {
                const token = localCache.getCache("token")
                if (token) {
                    interceptorsConfig.headers = Object.assign(interceptorsConfig.headers, {Authorization: token})
                } else {
                    // 重置并跳到登录
                    this.myModule.resetMyAction(interceptorsConfig.needNavigate)
                    this.needToast && Toast.fail("请先登录")
                }
            }
            this.needToast = !!interceptorsConfig?.needToast
            return interceptorsConfig;
        }, (error) => {
            return Promise.resolve(error);
        });

        // 添加响应拦截器
        this.request.interceptors.response.use(async (response) => {
            const data: IResponseData = response.data
            // 控制加载圈圈
            /*
            this.count -= 1
            if (this.count === 0) {
                this.toast.clear()
            }
            */
            // 判断状态
            if (data.code !== 0) {
                let errorMsg = "操作失败：" + response.data.msg
                if (data.code === -2) { // 未登录
                    // isLoginError = true
                    errorMsg = "请先登录"
                    this.myModule.resetMyAction()
                }
                this.needToast && Toast.fail(errorMsg)
            }
            return data;
        }, (error: AxiosError) => {
            this.count -= 1
            const err: IResponseData = {
                code: -1,
                msg: error.message,
                data: error
            }
            Toast.fail("请求失败" + error.message)
            return Promise.resolve(err);
        });
    }

    get(config: ZJRequestConfig) {
        const {url = "", ...realConfig} = config
        return this.request.get<any, IResponseData>(url, realConfig)
    }

    post(config: ZJRequestConfig) {
        const {url = "", data = {}, ...realConfig} = config
        return this.request.post<any, IResponseData>(url, data, realConfig)
    }

    put(config: ZJRequestConfig) {
        const {url = "", data = {}, ...realConfig} = config
        return this.request.put<any, IResponseData>(url, data, realConfig)
    }

    delete(config: ZJRequestConfig) {
        const {url = "", ...otherConfig} = config
        return this.request.delete<any, IResponseData>(url, otherConfig)
    }
}

export default ZJRequest
